from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from config import Config
from flask_cors import CORS

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
# 允许所有源
CORS(app)
#加一个东西123
# 定义数据模型
class Riddle(db.Model):
    __tablename__ = 'riddles'
    id = db.Column(db.Integer, primary_key=True)
    question = db.Column(db.String(200), nullable=False)
    answer = db.Column(db.String(200), nullable=False)
    
    def to_dict(self):
        return {
            'id': self.id,
            'question': self.question,
            'answer': self.answer
        }

# 路由
@app.route('/')
def index():
    return render_template('index.html')

# API接口
@app.route('/api/riddles', methods=['GET'])
def get_riddles():
    riddles = Riddle.query.all()
    return jsonify([riddle.to_dict() for riddle in riddles])

@app.route('/api/riddles', methods=['POST'])
def add_riddle():
    try:
        data = request.json
        if not data or '谜面' not in data or '谜底' not in data:
            return jsonify({'error': '缺少必要的字段'}), 400
            
        riddle = Riddle(
            question=data['谜面'],
            answer=data['谜底']
        )
        db.session.add(riddle)
        db.session.commit()
        return jsonify(riddle.to_dict())
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/riddles/<int:id>', methods=['PUT'])
def update_riddle(id):
    try:
        riddle = Riddle.query.get_or_404(id)
        data = request.json
        
        # 检查请求数据
        if not data or '谜面' not in data or '谜底' not in data:
            return jsonify({'error': '缺少必要的字段'}), 400
            
        # 更新数据
        riddle.question = data['谜面']
        riddle.answer = data['谜底']
        
        db.session.commit()
        return jsonify(riddle.to_dict())
        
    except Exception as e:
        # 添加日志以便调试
        print(f"更新谜语时出错: {str(e)}")
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@app.route('/api/riddles/<int:id>', methods=['DELETE'])
def delete_riddle(id):
    riddle = Riddle.query.get_or_404(id)
    db.session.delete(riddle)
    db.session.commit()
    return '', 204

@app.route('/api/riddles/random', methods=['GET'])
def get_random_riddle():
    # 随机获取一条脑筋急转弯
    riddle = Riddle.query.order_by(db.func.random()).first()
    if riddle:
        return jsonify(riddle.to_dict())
    return jsonify({'error': 'No riddles found'}), 404

@app.route('/api/riddles/random/<int:count>', methods=['GET'])
def get_random_riddles(count):
    # 随机获取指定数量的脑筋急转弯
    riddles = Riddle.query.order_by(db.func.random()).limit(count).all()
    if riddles:
        return jsonify([riddle.to_dict() for riddle in riddles])
    return jsonify({'error': 'No riddles found'}), 404

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True) 